package com.module.ble.ui.healthCheck

import android.os.CountDownTimer
import android.view.View
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.utls.HeadTitleUtils
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.formatToFloat
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.setText
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.listener.AlertDialogConfirmBtnListener
import com.common.base.utils.AppUtils
import com.common.base.utils.StatusBarUtils
import com.module.ble.R
import com.module.ble.databinding.BleActivityHealthDetectionBinding
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserHeartRate
import com.module.ble.listener.CusSynthesisHealthExpandListener
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.utils.CommonCusHealthType
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AizoSDKUtil.addSynthesisHealthExpandListener
import com.module.ble.utils.AizoSDKUtil.instantMeasurement
import com.module.ble.utils.AizoSDKUtil.removeSynthesisHealthExpandListener
import kotlinx.coroutines.launch

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2024/10/17
 * <p>
 * 描述：健康检测页面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_HEALTH_CHECK)
class HealthCheckActivity : AppActivity<BleActivityHealthDetectionBinding, HealthCheckViewModel>(),
    View.OnClickListener,
    CusConnectBleDeviceExpandListener, CusSynthesisHealthExpandListener {

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var mType: Int = CommonCusHealthType.HEARTRATE.value

    var isComplete = false

    private var mMaxCountDown = 65 * 1000L

    private var mBtnCountDownTimer: CountDownTimer? = null

    var macTemp: String? = null

    var curCheckValue =""
    var curCheckTime = 0L//此次测量时长

    override fun getViewModel() = HealthCheckViewModel::class.java

    override fun getViewContentBinding() = BleActivityHealthDetectionBinding.inflate(layoutInflater)

    override fun getPlaceholderView() = mViewBinding.mPlaceholderView

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle(when(mType){
            CommonCusHealthType.BLOODOXYGEN.value->getString(R.string.ble_health_blo_oxy_title)
            CommonCusHealthType.BODYTEMP.value->getString(R.string.ble_health_body_temper_title)
            else -> getString(R.string.ble_health_health_rate_title)
        })
    }

    override fun initEvents() {
        super.initEvents()

        AizoSDKUtil.addConnectBleDeviceExpandListener(this)
        addSynthesisHealthExpandListener(this)

        mViewContentBinding.tvSwitch.setOnClickListener(onClick = this)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        macTemp = AizoSDKUtil.getBleBindingMac()

        when(mType){
            CommonCusHealthType.BLOODOXYGEN.value->{
                setText(mViewContentBinding.tvHealthValueHint, getString(R.string.ble_health_at_present_split,getString(R.string.ble_health_blo_oxy_title)))
                mViewContentBinding.imgHealthType.setImageResource(R.drawable.ble_shark_blood_oxygen_mc)
                mViewContentBinding.imgStroke.setImageResource(R.drawable.ble_measure_result_bo_scope)
            }
            CommonCusHealthType.BODYTEMP.value->{
                setText(mViewContentBinding.tvHealthValueHint, getString(R.string.ble_health_at_present_split,getString(R.string.ble_health_body_temper_title)))
                mViewContentBinding.imgHealthType.setImageResource(R.drawable.ble_shark_temperature_mc)
                mViewContentBinding.imgStroke.setImageResource(R.drawable.ble_measure_result_tp_scope)
            }
            else -> {
                setText(mViewContentBinding.tvHealthValueHint, getString(R.string.ble_health_at_present_split,getString(R.string.ble_health_health_rate_title)))
                mViewContentBinding.imgHealthType.setImageResource(R.drawable.ble_shark_heart_rate_mc)
                mViewContentBinding.imgStroke.setImageResource(R.drawable.ble_measure_result_hr_scope)
            }
        }

    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.tvSwitch -> {
                if(!AizoSDKUtil.isConnect()){
                    showToast(getString(R.string.ble_device_disconnect))
                    return
                }
                when(mViewContentBinding.tvSwitch.text.toString()){
                    getString(R.string.ok_btn_zh2)-> finish()
                    getString(R.string.ble_health_retest_check_cancel)->{
                        showAlertDialogTwoBtn(
                            getString(R.string.cancel_btn_zh2),
                            getString(R.string.ok_btn_zh),
                            getString(R.string.ble_health_check_cancel),
                            getString(R.string.ble_health_check_cancel_body),
                            message2="",true, object :
                                AlertDialogConfirmBtnListener {
                                override fun onCancelBtnClick() {
                                }

                                override fun onConfirmBtnClick() {
                                    instantMeasurement(mType, 2)
                                    finish()
                                }
                            }
                        )
                    }
                    else ->{
                        setVisibility(mViewContentBinding.tvCheckTime, false)
                        setVisibility(mViewContentBinding.imgFail, false)
                        setVisibility(mViewContentBinding.tvLoading, true)
                        setVisibility(mViewContentBinding.tvNotice, true)
                        setVisibility(mViewContentBinding.bleAnimation, true)
                        changeMeasureUi(AizoSDKUtil.isConnect(),true)
                        createCountDownTimer()
                        instantMeasurement(mType)
                        setText(mViewContentBinding.tvLoading, getString(R.string.ble_health_check_run))
                        setText(mViewContentBinding.tvSwitch, getString(R.string.ble_health_retest_check_cancel))
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        removeSynthesisHealthExpandListener(this)
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer= null
        AizoSDKUtil.removeConnectBleDeviceExpandListener(this)
        super.onDestroy()
    }

    private fun createCountDownTimer() {
        isComplete = false
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer= null
        mBtnCountDownTimer = object : CountDownTimer(mMaxCountDown, 1000L) {
                override fun onTick(millisUntilFinished: Long) {
                }

                override fun onFinish() {
                    isComplete.yes {
                        changeMeasureUi()
                        setVisibility(mViewContentBinding.tvLoading, false)
                        setVisibility(mViewContentBinding.tvNotice, false)
                        setVisibility(mViewContentBinding.tvCheckTime, true)
                        setVisibility(mViewContentBinding.tvReferenceHint, true)
                        setVisibility(mViewContentBinding.totalComplete, true)
                        setText(mViewContentBinding.tvHealthValue, curCheckValue+when(mType){
                            CommonCusHealthType.BLOODOXYGEN.value->getString(R.string.common_heart_rate_unit)
                            CommonCusHealthType.BODYTEMP.value->getString(R.string.common_ssd_unit)
                            else ->""})
                        setText(mViewContentBinding.tvCheckTime, getString(R.string.ble_health_check_time_split, TimeUtils.getYearMonthDayHourMinute(curCheckTime)))
                        setText(mViewContentBinding.tvSwitch, getString(R.string.ok_btn_zh2))
                    }.otherwise {
                        changeMeasureUi()
                        setText(mViewContentBinding.tvLoading, getString(R.string.ble_health_check_fail))
                        setText(mViewContentBinding.tvSwitch, getString(R.string.ble_health_retest_check_run))
                        setVisibility(mViewContentBinding.tvReferenceHint, false)
                        setVisibility(mViewContentBinding.tvCheckTime, false)
                        setVisibility(mViewContentBinding.tvLoading, true)
                        setVisibility(mViewContentBinding.tvNotice, true)
                        setVisibility(mViewContentBinding.imgFail, true)
                    }
                }
            }
        mBtnCountDownTimer?.start()
    }

    private fun changeMeasureUi(show: Boolean = false, play:Boolean = false) {
        show.yes {
            setVisibility(mViewContentBinding.bleAnimation, show)
        }.otherwise {
            mViewContentBinding.bleAnimation.visibility = View.INVISIBLE
        }

        play.yes {
            mViewContentBinding.bleAnimation.playAnimation()
        }.otherwise {
            mViewContentBinding.bleAnimation.pauseAnimation()
            mViewContentBinding.bleAnimation.frame = 0// 恢复到第一帧
            mViewContentBinding.bleAnimation.cancelAnimation()
        }
    }

    override fun onConnect(macStr: String?) {
    }

    override fun onConnectError(macStr: String?, throwable: Throwable?, state: Int) {
        isComplete = false
        changeMeasureUi()
        setText(mViewContentBinding.tvSwitch, getString(R.string.ble_health_retest_check_run))
    }

    override fun onDisconnect(macStr: String?) {
        isComplete = false
        changeMeasureUi()
        setText(mViewContentBinding.tvSwitch, getString(R.string.ble_health_retest_check_run))

    }

    override fun onHandleDevice(type: Int, result: Boolean) {
    }

    override fun onBoundDeviceResult(macStr: String, result: Boolean) {
    }

    override fun onMeasureResult(
        result: Boolean,
        type: Int,
        time: Long,
        heartRate: Int,
        bloodOxygen: Int,
        bodyTemp: Float,
        envTemp: Float
    ) {
        isComplete = result
        curCheckTime = time
        when (type) {
            1 -> {
                curCheckValue = heartRate.toString()
            }
            2 -> {
                curCheckValue = bloodOxygen.toString()
            }
            6 -> {
                curCheckValue = bodyTemp.formatToFloat(1).toString()
            }
        }
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer?.onFinish()
        mBtnCountDownTimer= null
    }

    override fun onLatestHr(value: Int, macStr: String, time: Long) {
    }

    override fun onHeartRateDataListResult(result: List<UserHeartRate>) {
    }

    override fun getLatestBloodOxygen(value: Int, macStr: String, time: Long) {
    }

    override fun onBloodOxygenDataListResult(result: List<UserBloodOxygen>) {
    }

    override fun onLatestBodyTemper(value: Float, macStr: String, time: Long) {
    }

    override fun onBodyTemperDataListResult(result: List<UserBodyTemperature>) {
    }

}